<?php
class Opreation {
    private $path;

    public function __construct($path) {
            $this->path = $path;
    }

    /**
     * 生成文件名
     * @return \Generator
     */
    public function base_file()
    {
        $res = [];
        // 获取某目录下所有文件、目录名（不包括子目录下文件、目录名）
        $handler = opendir($this->path);
        while (($filename = readdir($handler)) !== false) {
            // 务必使用!==，防止目录下出现类似文件名“0”等情况
            if ($filename !== "." && $filename !== "..") {
                $res[filectime($this->path.'/'. $filename)] = $filename;
            }
        }
        krsort($res);
        closedir($handler);
        return $res;
    }

    /**
     * 过滤md文件
     */
    public function filter_md($path_name,$analyize_name){
        $file = fopen($path_name,'r');
        $i = 0;
        $result = "";
        while(!feof($file)) {
            $line_str = fgets($file);
            if (strpos($line_str,$analyize_name) !== false) {
                $result = $line_str;
            }
            $i ++;
        }
        fclose($file);
        $res = trim(explode(':', $result)[1]);
        if (strpos($res,'[') !== false) {
            $res = implode('/',explode(',',str_replace(']', '',str_replace('[', '',$res))));
        } else {
            $res = str_replace('"', '',$res);
        }
        return $res;
    }

	public function get_content($path_name)
	{
		
		$file = fopen($path_name,'r');
		$data = file_get_contents($path_name);
		var_dump($data);exit;
        $i = 0;
        $result = "";
        while(!feof($file)) {
            $line_str = fgets($file);
            if (strpos($line_str,"--") !== false) {
				$i ++;
            }
			var_dump($line_str );exit;
			if ($i > 2) {
				
				$result .= $line_str;
			}
            
        }
        fclose($file);
		var_dump($result );exit;
        $res = trim(explode(':', $result)[1]);
        if (strpos($res,'[') !== false) {
            $res = implode('/',explode(',',str_replace(']', '',str_replace('[', '',$res))));
        } else {
            $res = str_replace('"', '',$res);
        }
        return $res;
	}
    /**
     * 生成目录
     */
    public function generate_path() {
        $data = [];
        foreach($this->base_file() as $k=>$v){
            $regex="'\d{4}-\d{1,2}-\d{1,2}'is";
			$this->get_content('./_posts/'.$v);
            preg_match($regex,$v,$matche);
            $thename = explode($matche[0],$v);
            $subs = substr($thename[1],1);
            $resultStr = substr($subs,0,strlen($subs)-3);
            $data[$k] = [
                'url'=>'/'.implode('/',array_merge([$this->filter_md('./_posts/'.$v,'categories')],[
                    str_replace('-','/',$matche[0]),
                    $resultStr,
                    
                ])).'.html',
                'title'=> $this->filter_md('./_posts/'.$v,'title'),
            ];
        }
        return $data;
    }
}

$op = new Opreation('./_posts');
$path = $op->generate_path();

?>